import urllib
import logging
import re
import cgi
from datetime import datetime
import time

import feedparser
import item

from google.appengine.ext import webapp
from google.appengine.api.urlfetch import fetch

try:
  # This is where simplejson lives on App Engine
  from django.utils import simplejson
except (ImportError):
  import simplejson

GARDENHOSE = "https://www.googleapis.com/buzz/v1/activities/@all/@public?mode=trickle"
HUB = "http://pubsubhubbub.appspot.com/"

# This callback must be changed for your application
# replace "buzz-gardenstarter" with your app's name
CALLBACK = "http://buzz-gardenstarter.appspot.com/pshb/callback"

DATE_FORMAT = "%a, %d %b %Y %H:%M:%S GMT"

class PubsubhubbubSubscribeHandler(webapp.RequestHandler):
  def get(self):
    self.post()

  def post(self):
    parameters = {
      "hub.callback": CALLBACK,
      "hub.mode": "subscribe",
      "hub.topic": GARDENHOSE,
      "hub.verify": "async"
    }
    fetch(
      HUB,
      method='POST',
      payload=urllib.urlencode(parameters),
      follow_redirects=False
    )

class PubsubhubbubCallbackHandler(webapp.RequestHandler):
  def get(self):
    # Verify request
    hub_mode = self.request.get('hub.mode')
    hub_topic = self.request.get('hub.topic')
    hub_challenge = self.request.get('hub.challenge')
    hub_lease_seconds = self.request.get('hub.lease_seconds')
    hub_verify_token = self.request.get('hub.verify_token')

    if hub_mode == "subscribe":
      if hub_topic == GARDENHOSE:
        logging.info('Subscription verified.')
        self.response.set_status(202)
        self.response.out.write(hub_challenge)
      else:
        # We're only interested in the gardenhose
        self.response.set_status(403)
        self.response.out.write('')
    else:
      # We don't really ever unsubscribe
      self.response.set_status(403)
      self.response.out.write('')

  def post(self):
    # New content pushed
    feed_data = self.request.body
    feed = feedparser.parse(feed_data)
    for entry in feed.entries:
      if hasattr(entry, 'content') and entry.content[0].value != "":
        content = entry.content[0].value
      else:
        logging.info('Skipping, couldn\'t find content.')
        continue
        
      if hasattr(entry, 'author') and entry.author != "":
        author = entry.author
      else:
        logging.info('Skipping, couldn\'t find author.')
        continue
        
      if hasattr(entry, 'link') and entry.link != "":
        link = entry.link
      else:
        logging.info('Skipping, couldn\'t find link.')
        continue
        
      if hasattr(entry, 'updated_parsed') and entry.updated_parsed != "":
        updated = time.mktime(entry.updated_parsed)
      else:
        logging.info('Skipping, couldn\'t find time.')
        continue
      
      item.make_item(content, author, link, updated)
